package com.rm.zeyou.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.DesensitizedUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rm.zeyou.constant.CommonConstants;
import com.rm.zeyou.constant.NumberConstants;
import com.rm.zeyou.constant.RedisConstants;
import com.rm.zeyou.entity.*;
import com.rm.zeyou.exception.ErrorCodeException;
import com.rm.zeyou.exception.ErrorCodeExceptionEnum;
import com.rm.zeyou.mapper.*;
import com.rm.zeyou.pay.wxpay.entity.GetAccessTokenByCodeBean;
import com.rm.zeyou.pay.wxpay.entity.GetUserInfoBean;
import com.rm.zeyou.pay.wxpay.service.WechatAppLoginService;
import com.rm.zeyou.pay.wxpay.service.WechatH5LoginService;
import com.rm.zeyou.response.ApiRestResponse;
import com.rm.zeyou.service.UserService;
import com.rm.zeyou.util.check.CheckEmptyUtil;
import com.rm.zeyou.util.data.DataDesensitizedUtil;
import com.rm.zeyou.util.login.LoginUtil;
import com.rm.zeyou.util.login.StpKit;
import com.rm.zeyou.util.redis.RedisUtil;
import com.rm.zeyou.vo.request.UpdateUserVo;
import com.rm.zeyou.vo.request.UserBindTelVo;
import com.rm.zeyou.vo.request.UserCodeLoginVo;
import com.rm.zeyou.vo.request.UserWXLoginVo;
import com.rm.zeyou.vo.response.PersonalCenterResponseVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author YanYang
 * @since 2025-03-12 15:55:09
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Resource
    private UserMapper userMapper;
    @Resource
    private RedisUtil redisUtil;
    @Resource
    private LoginUtil loginUtil;
    @Resource
    private DictConfigMapper dictConfigMapper;
    @Resource
    private WechatH5LoginService wechatH5LoginService;
    @Resource
    private WechatAppLoginService wechatAppLoginService;
    @Resource
    private UserCouponMapper userCouponMapper;
    @Resource
    private UserBackMapper userBackMapper;
    @Resource
    private UserAttentionMapper userAttentionMapper;
    @Resource
    private UserCollectionMapper userCollectionMapper;
    @Resource
    private TechnicianMapper technicianMapper;
    @Resource
    private CouponConfigMapper couponConfigMapper;
    @Resource
    private UserMemberMapper userMemberMapper;
    @Resource
    private SalesmanApplyMapper salesmanApplyMapper;
    @Resource
    private ChannelApplyMapper channelApplyMapper;
    @Resource
    private MessageMapper messageMapper;

    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public ApiRestResponse<Map<String, String>> userCodeLogin(UserCodeLoginVo loginVo) {
        //校验验证码
        checkCode(loginVo.getTel(), loginVo.getCode(), CommonConstants.SMS_USER_LOGIN);

        //通过手机号查询用户是否注册
        User user = userMapper.selectUser(loginVo.getTel());
        if (!CheckEmptyUtil.isEmpty(user)) {
            StpKit.USER.checkDisable(user.getId());

            //已注册 直接登录
            Map<String, String> token = loginUtil.getToken(user.getId());
            token.put("isBindTel", String.valueOf(NumberConstants.ONE_CONSTANTS));
            if (CheckEmptyUtil.isEmpty(user.getOpenId())) {
                token.put("isBindWx", String.valueOf(NumberConstants.ZERO_CONSTANTS));
            } else {
                token.put("isBindWx", String.valueOf(NumberConstants.ONE_CONSTANTS));
            }

            if (CheckEmptyUtil.isEmpty(user.getAppOpenId())) {
                token.put("isBindWxApp", String.valueOf(NumberConstants.ZERO_CONSTANTS));
            } else {
                token.put("isBindWxApp", String.valueOf(NumberConstants.ONE_CONSTANTS));
            }
            token.put("isFirstLogin", String.valueOf(user.getIsFirstLogin()));
            //修改第一次登录信息
            userMapper.updateFirstLogin(user.getId());
            return ApiRestResponse.success(token);
        } else {
            String defaultAvatar = dictConfigMapper.defaultAvatar();
            String defaultNikename = dictConfigMapper.defaultNikename();
            //未注册
            User insertUser = new User();
            insertUser.setUserAvatar(defaultAvatar);
            insertUser.setUserNikeName(defaultNikename);
            insertUser.setUserTel(loginVo.getTel());
            insertUser.setUserInvitationCode(UUID.randomUUID().toString().replaceAll("-", "").substring(0, 8));
            //insertUser.setUserId(getUserId());
            if (!CheckEmptyUtil.isEmpty(loginVo.getUserInvitedCode())) {
                insertUser.setUserInvitedCode(loginVo.getUserInvitedCode());
                //查上级用户
                User invitationUser = userMapper.selectOne(new LambdaQueryWrapper<User>()
                        .eq(User::getUserInvitationCode, loginVo.getUserInvitedCode()));
                if (CheckEmptyUtil.isEmpty(invitationUser)) {
                    throw new ErrorCodeException(ErrorCodeExceptionEnum.INVITATED_CODE_ERROR);
                }
                // TODO 如果有邀请奖励
                //UserInvite userInvite = new UserInvite();
                //userInvite.setInvitionUserId(invitationUser.getId());
                //userInvite.setInvitedUserId(insertUser.getId());
                //userInvite.setInviteAmot(new BigDecimal(0));
                //userInviteMapper.insert(userInvite);

            }
            if (!CheckEmptyUtil.isEmpty(loginVo.getLoginType()) && loginVo.getLoginType() != -1) {
                insertUser.setUserSource(loginVo.getLoginType());
            }
            userMapper.insert(insertUser);
            getNewCoupon(insertUser.getId());
            User user1 = userMapper.selectById(insertUser.getId());
            //返回登录信息
            Map<String, String> token = loginUtil.getToken(insertUser.getId());
            token.put("isBindTel", String.valueOf(NumberConstants.ONE_CONSTANTS));
            token.put("isBindWx", String.valueOf(NumberConstants.ZERO_CONSTANTS));
            token.put("isBindWxApp", String.valueOf(NumberConstants.ZERO_CONSTANTS));
            token.put("isFirstLogin", String.valueOf(user1.getIsFirstLogin()));
            //修改第一次登录信息
            userMapper.updateFirstLogin(insertUser.getId());
            return ApiRestResponse.success(token);
        }

    }

    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public ApiRestResponse<Map<String, String>> userWXLogin(UserWXLoginVo loginVo) {
        GetAccessTokenByCodeBean accessToken = wechatH5LoginService.getAccessToken(loginVo.getCode());
        log.info("accessToken:[{}]", accessToken);
        GetUserInfoBean userInfo = wechatH5LoginService.getUserInfo(accessToken.getOpenid(), accessToken.getAccessToken());
        log.info("userInfo:[{}]", userInfo);
        if (CheckEmptyUtil.isEmpty(userInfo)) {
            throw new ErrorCodeException(ErrorCodeExceptionEnum.WX_LOGIN_ERROR);
        }
        //通过openid查询用户是否存在
        User userDetails = userMapper.selectUserByOpenId(userInfo.getUnionid());
        if (CheckEmptyUtil.isEmpty(userDetails)) {
            //注册并登录
            User insertUser = new User();
            insertUser.setUserAvatar(userInfo.getHeadimgurl());
            insertUser.setUserNikeName(userInfo.getNickname());
            insertUser.setOpenId(userInfo.getOpenid());
            insertUser.setUserWxName(userInfo.getNickname());
            insertUser.setUnionid(userInfo.getUnionid());
            insertUser.setUserInvitationCode(UUID.randomUUID().toString().replaceAll("-", "").substring(0, 8));
            //insertUser.setUserId(getUserId());
            if (!CheckEmptyUtil.isEmpty(loginVo.getUserInvitedCode())) {
                insertUser.setUserInvitedCode(loginVo.getUserInvitedCode());

                //查上级用户
                User invitationUser = userMapper.selectOne(new LambdaQueryWrapper<User>()
                        .eq(User::getUserInvitationCode, loginVo.getUserInvitedCode()));
                if (CheckEmptyUtil.isEmpty(invitationUser)) {
                    throw new ErrorCodeException(ErrorCodeExceptionEnum.INVITATED_CODE_ERROR);
                }
                // TODO 如果有邀请奖励
                //UserInvite userInvite = new UserInvite();
                //userInvite.setInvitionUserId(invitationUser.getId());
                //userInvite.setInvitedUserId(insertUser.getId());
                //userInvite.setInviteAmot(new BigDecimal(0));
                //userInviteMapper.insert(userInvite);

            }
            if (!CheckEmptyUtil.isEmpty(loginVo.getLoginType()) && loginVo.getLoginType() != -1) {
                insertUser.setUserSource(loginVo.getLoginType());
            }
            userMapper.insert(insertUser);
            getNewCoupon(insertUser.getId());
            User user1 = userMapper.selectById(insertUser.getId());
            //返回登录信息
            Map<String, String> token = loginUtil.getToken(insertUser.getId());
            token.put("isBindTel", String.valueOf(NumberConstants.ZERO_CONSTANTS));
            token.put("isBindWx", String.valueOf(NumberConstants.ONE_CONSTANTS));
            token.put("isFirstLogin", String.valueOf(user1.getIsFirstLogin()));
            //修改第一次登录信息
            userMapper.updateFirstLogin(insertUser.getId());
            return ApiRestResponse.success(token);
        } else {
            StpKit.USER.checkDisable(userDetails.getId());
            //已注册 直接登录
            Map<String, String> token = loginUtil.getToken(userDetails.getId());
            token.put("isBindWx", String.valueOf(NumberConstants.ONE_CONSTANTS));
            if (CheckEmptyUtil.isEmpty(userDetails.getUserTel())) {
                token.put("isBindTel", String.valueOf(NumberConstants.ZERO_CONSTANTS));
            } else {
                token.put("isBindTel", String.valueOf(NumberConstants.ONE_CONSTANTS));
            }
            token.put("isFirstLogin", String.valueOf(userDetails.getIsFirstLogin()));
            //修改第一次登录信息
            userMapper.updateFirstLogin(userDetails.getId());
            return ApiRestResponse.success(token);
        }
    }

    @Override
    public ApiRestResponse userAPPWXLogin(UserWXLoginVo loginVo) {
        GetAccessTokenByCodeBean accessToken = wechatAppLoginService.getAccessToken(loginVo.getCode(), 1);
        log.info("accessToken:[{}]", accessToken);
        GetUserInfoBean userInfo = wechatAppLoginService.getUserInfo(accessToken.getOpenid(), accessToken.getAccessToken());
        log.info("userInfo:[{}]", userInfo);
        if (CheckEmptyUtil.isEmpty(userInfo)) {
            throw new ErrorCodeException(ErrorCodeExceptionEnum.WX_LOGIN_ERROR);
        }
        //通过openid查询用户是否存在
        User userDetails = userMapper.selectUserByOpenId(userInfo.getUnionid());
        if (CheckEmptyUtil.isEmpty(userDetails)) {

            //注册并登录
            User insertUser = new User();
            insertUser.setUserAvatar(userInfo.getHeadimgurl());
            insertUser.setUserNikeName(userInfo.getNickname());
            insertUser.setAppOpenId(userInfo.getOpenid());
            insertUser.setUserWxName(userInfo.getNickname());
            insertUser.setUnionid(userInfo.getUnionid());
            insertUser.setUserInvitationCode(UUID.randomUUID().toString().replaceAll("-", "").substring(0, 8));
            //insertUser.setUserId(getUserId());
            if (!CheckEmptyUtil.isEmpty(loginVo.getUserInvitedCode())) {
                insertUser.setUserInvitedCode(loginVo.getUserInvitedCode());

                //查上级用户
                User invitationUser = userMapper.selectOne(new LambdaQueryWrapper<User>()
                        .eq(User::getUserInvitationCode, loginVo.getUserInvitedCode()));
                if (CheckEmptyUtil.isEmpty(invitationUser)) {
                    throw new ErrorCodeException(ErrorCodeExceptionEnum.INVITATED_CODE_ERROR);
                }
                // TODO 如果有邀请奖励
                //UserInvite userInvite = new UserInvite();
                //userInvite.setInvitionUserId(invitationUser.getId());
                //userInvite.setInvitedUserId(insertUser.getId());
                //userInvite.setInviteAmot(new BigDecimal(0));
                //userInviteMapper.insert(userInvite);

            }
            if (!CheckEmptyUtil.isEmpty(loginVo.getLoginType()) && loginVo.getLoginType() != -1) {
                insertUser.setUserSource(loginVo.getLoginType());
            }
            userMapper.insert(insertUser);
            getNewCoupon(insertUser.getId());
            //返回登录信息
            Map<String, String> token = loginUtil.getToken(insertUser.getId());
            token.put("isBindTel", String.valueOf(NumberConstants.ZERO_CONSTANTS));
            token.put("isBindWx", String.valueOf(NumberConstants.ONE_CONSTANTS));
            return ApiRestResponse.success(token);
        } else {
            userDetails.setAppOpenId(userInfo.getOpenid());
            userDetails.setUserWxName(userInfo.getNickname());
            userMapper.updateById(userDetails);
            StpKit.USER.checkDisable(userDetails.getId());
            //已注册 直接登录
            Map<String, String> token = loginUtil.getToken(userDetails.getId());
            token.put("isBindWx", String.valueOf(NumberConstants.ONE_CONSTANTS));
            if (CheckEmptyUtil.isEmpty(userDetails.getUserTel())) {
                token.put("isBindTel", String.valueOf(NumberConstants.ZERO_CONSTANTS));
            } else {
                token.put("isBindTel", String.valueOf(NumberConstants.ONE_CONSTANTS));
            }
            return ApiRestResponse.success(token);
        }
    }

    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public ApiRestResponse<Integer> updateUser(User user, UpdateUserVo updateVo) {
        if (!CheckEmptyUtil.isEmpty(updateVo.getUserSex())) {
            user.setUserSex(updateVo.getUserSex());
        }
        if (!CheckEmptyUtil.isEmpty(updateVo.getUserNikeName())) {
            if (!DataDesensitizedUtil.validateString(updateVo.getUserNikeName())) {
                throw new ErrorCodeException(ErrorCodeExceptionEnum.NAME_ERROR);
            }
            user.setUserNikeName(updateVo.getUserNikeName());
        }
        if (!CheckEmptyUtil.isEmpty(updateVo.getUserAvatar())) {
            user.setUserAvatar(updateVo.getUserAvatar());
        }
        int i = userMapper.updateById(user);
        return ApiRestResponse.success(i);
    }

    @Override
    public ApiRestResponse<Void> userLoginOut(Long userId) {
        String redisUserTokenKey = RedisConstants.USER_LOGIN_TOKEN + userId;
        redisUtil.del(redisUserTokenKey);
        return ApiRestResponse.success();
    }

    @Override
    public ApiRestResponse<PersonalCenterResponseVo> personalCenter(User user) {
        PersonalCenterResponseVo responseVo = new PersonalCenterResponseVo();

        responseVo.setId(user.getId());
        responseVo.setUserTel(DesensitizedUtil.mobilePhone(user.getUserTel()));
        responseVo.setUserSex(user.getUserSex());
        responseVo.setUserAvatar(user.getUserAvatar());
        responseVo.setUserNikeName(user.getUserNikeName());
        responseVo.setUserBalance(user.getUserBalance());
        int isVip = userMemberMapper.selectCount(new LambdaQueryWrapper<UserMember>()
                .eq(UserMember::getUserId, user.getId())).intValue();
        responseVo.setIsVip(isVip);

        Technician technician = technicianMapper.selectOne(new LambdaQueryWrapper<Technician>()
                .eq(Technician::getUserId, user.getId()));
        if (CheckEmptyUtil.isEmpty(technician)) {
            responseVo.setIsTechnician(NumberConstants.ZERO_CONSTANTS);
        } else {
            responseVo.setIsTechnician(NumberConstants.ONE_CONSTANTS);
        }
        if (user.getUserIdentity().equals(NumberConstants.ONE_CONSTANTS)) {
            responseVo.setIsSalesman(NumberConstants.ONE_CONSTANTS);
        } else {
            int value = salesmanApplyMapper.selectCount(new LambdaQueryWrapper<SalesmanApply>()
                    .eq(SalesmanApply::getUserId, user.getId())
                    .eq(SalesmanApply::getAuditStatus, NumberConstants.ZERO_CONSTANTS)).intValue();
            if (value > 0) {
                responseVo.setIsSalesman(NumberConstants.TWO_CONSTANTS);
            } else {
                responseVo.setIsSalesman(NumberConstants.ZERO_CONSTANTS);
            }
        }
        if (user.getUserIdentity().equals(NumberConstants.TWO_CONSTANTS)) {
            responseVo.setIsChannel(NumberConstants.ONE_CONSTANTS);
        } else {
            int value = channelApplyMapper.selectCount(new LambdaQueryWrapper<ChannelApply>()
                    .eq(ChannelApply::getUserId, user.getId())
                    .eq(ChannelApply::getAuditStatus, NumberConstants.ZERO_CONSTANTS)).intValue();
            if (value > 0) {
                responseVo.setIsChannel(NumberConstants.TWO_CONSTANTS);
            } else {
                responseVo.setIsChannel(NumberConstants.ZERO_CONSTANTS);
            }

        }
        //关注数
        responseVo.setAttentionCount(userAttentionMapper.selectAttentionCount(user.getId()));
        //优惠券数量
        responseVo.setUserCouponCount(userCouponMapper.selectCouponCount(user.getId()));
        //银行卡数量
        responseVo.setUserBackCount(userBackMapper.selectBackCount(user.getId()));
        //收藏数量
        responseVo.setCollectionCount(userCollectionMapper.selectrCollectionCount(user.getId()));
        int messageCount = messageMapper.selectCount(new LambdaQueryWrapper<Message>()
                .eq(Message::getUserId, user.getId())
                .eq(Message::getIsRead, NumberConstants.ZERO_CONSTANTS)).intValue();
        responseVo.setMessageCount(messageCount);
        return ApiRestResponse.success(responseVo);
    }

    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public ApiRestResponse<Integer> userBindTel(User user, UserBindTelVo bindTelVo) {
        checkCode(bindTelVo.getTel(), bindTelVo.getCode(), CommonConstants.USER_BLIND_TEL);
        //查询手机号是否已绑定
        User user1 = userMapper.selectOne(new LambdaQueryWrapper<User>()
                .eq(User::getUserTel, bindTelVo.getTel()));
        if (!CheckEmptyUtil.isEmpty(user1)) {
            throw new ErrorCodeException(ErrorCodeExceptionEnum.TEL_IS_BING);
        }
        user.setUserTel(bindTelVo.getTel());
        return ApiRestResponse.success(userMapper.updateById(user));
    }

    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public ApiRestResponse userBindWx(User user, UserBindTelVo bindTelVo) {
        GetAccessTokenByCodeBean accessToken = wechatH5LoginService.getAccessToken(bindTelVo.getCode());
        log.info("accessToken:[{}]", accessToken);
        GetUserInfoBean userInfo = wechatH5LoginService.getUserInfo(accessToken.getOpenid(), accessToken.getAccessToken());
        log.info("userInfo:[{}]", userInfo);
        if (CheckEmptyUtil.isEmpty(userInfo)) {
            throw new ErrorCodeException(ErrorCodeExceptionEnum.WX_LOGIN_ERROR);
        }
        //查询微信是否已绑定
        User user1 = userMapper.selectOne(new LambdaQueryWrapper<User>()
                .eq(User::getOpenId, userInfo.getOpenid()));
        if (!CheckEmptyUtil.isEmpty(user1)){
            throw new ErrorCodeException(ErrorCodeExceptionEnum.WX_IS_BIND);
        }
        user.setOpenId(userInfo.getOpenid());
        user.setUserWxName(userInfo.getNickname());
        user.setUserNikeName(userInfo.getNickname());
        user.setUserAvatar(userInfo.getHeadimgurl());
        user.setUnionid(userInfo.getUnionid());
        //如果之前有人绑定此微信  将之前微信账号删除
        //User user1 = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getOpenId, userInfo.getOpenid()));
        //if (!CheckEmptyUtil.isEmpty(user1)) {
        //    userMapper.deleteUser(user1.getId());
        //}
        return ApiRestResponse.success(userMapper.updateById(user));

    }

    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public ApiRestResponse userAPPBindWx(User user, UserBindTelVo bindTelVo) {
        GetAccessTokenByCodeBean accessToken = wechatAppLoginService.getAccessToken(bindTelVo.getCode(), 1);
        log.info("accessToken:[{}]", accessToken);
        GetUserInfoBean userInfo = wechatAppLoginService.getUserInfo(accessToken.getOpenid(), accessToken.getAccessToken());
        log.info("userInfo:[{}]", userInfo);
        if (CheckEmptyUtil.isEmpty(userInfo)) {
            throw new ErrorCodeException(ErrorCodeExceptionEnum.WX_LOGIN_ERROR);
        }
        //查询微信是否已绑定
        User user1 = userMapper.selectOne(new LambdaQueryWrapper<User>()
                .eq(User::getAppOpenId, userInfo.getOpenid()));
        if (!CheckEmptyUtil.isEmpty(user1)){
            throw new ErrorCodeException(ErrorCodeExceptionEnum.WX_IS_BIND);
        }
        user.setAppOpenId(userInfo.getOpenid());
        user.setUserWxName(userInfo.getNickname());
        user.setUserNikeName(userInfo.getNickname());
        user.setUserAvatar(userInfo.getHeadimgurl());
        user.setUnionid(userInfo.getUnionid());
        //如果之前有人绑定此微信  将之前微信账号删除
        //User user1 = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getOpenId, userInfo.getOpenid()));
        //if (!CheckEmptyUtil.isEmpty(user1)) {
        //    userMapper.deleteUser(user1.getId());
        //}
        return ApiRestResponse.success(userMapper.updateById(user));

    }

    /**
     * 校验验证码是否正确
     *
     * @param tel  手机号
     * @param code 验证码
     * @param type 验证码类型
     * @Date 2025 2月28 16:16
     */
    @Override
    public void checkCode(String tel, String code, String type) {
        if (CheckEmptyUtil.isEmpty(tel)) {
            throw new ErrorCodeException(ErrorCodeExceptionEnum.PHONE_NUMBER_EMPTY);
        }
        //boolean validPhoneNumber = Validator.isMobile(tel);
        //if (Boolean.FALSE.equals(validPhoneNumber)) {
        //    throw new ErrorCodeException(ErrorCodeExceptionEnum.PHONE_NUMBER_ERROR);
        //}

        if (CheckEmptyUtil.isEmpty(code)) {
            throw new ErrorCodeException(ErrorCodeExceptionEnum.CODE_EMPTY);
        }
        String resultCode = redisUtil.get(type + tel);
        log.info("缓存中的验证码:{}", resultCode);
        if (CheckEmptyUtil.isEmpty(resultCode)) {
            throw new ErrorCodeException(ErrorCodeExceptionEnum.REDIS_CODE_EMPTY);
        }
        if (!resultCode.equals(code)) {
            throw new ErrorCodeException(ErrorCodeExceptionEnum.CODE_ERROR);
        }
    }

    /**
     * 设置用户6位数ID
     *
     * @return 六位数ID
     * @Date 2025 2月 28 16:17
     */
    private String getUserId() {
        String redisKey = "UserIdKey";
        String userId = redisUtil.get(redisKey);
        if (CheckEmptyUtil.isEmpty(userId)) {
            redisUtil.set(redisKey, "100000");
        } else {
            long id = Long.parseLong(userId);
            redisUtil.set(redisKey, String.valueOf(id + 1));
        }
        return redisUtil.get(redisKey);
    }

    /**
     * 赠送新人优惠券
     *
     * @param userId
     * @Date 2025 3月 03 14:16
     */
    private void getNewCoupon(Long userId) {
        String redisKey = "user_coupon";
        Map<String, Object> map = new HashMap<>();
        AtomicReference<Integer> couponCount = new AtomicReference<>(0);
        ArrayList<UserCoupon> list = new ArrayList<>();
        //查询是否有新人优惠券
        List<CouponConfig> couponConfigs = couponConfigMapper.selectNewCouponList();
        if (!CheckEmptyUtil.isEmpty(couponConfigs)) {
            couponConfigs.forEach(item -> {
                //剩余可领优惠券数量
                int total = Math.min(item.getCouponLimitReceiveTotal(), item.getCouponTotal());
                for (int i = 0; i < total; i++) {
                    UserCoupon userCoupon = new UserCoupon();
                    userCoupon.setUserId(userId);
                    userCoupon.setCouponId(item.getId());
                    userCoupon.setCoupomScopeApplication(item.getCouponScopeApplication());
                    userCoupon.setCloseTime(DateUtil.offsetDay(new Date(), item.getEffectDay()));
                    userCoupon.setCouponFull(item.getCouponFull());
                    userCoupon.setCouponSubtract(item.getCouponSubtract());
                    list.add(userCoupon);
                    userCouponMapper.insert(userCoupon);
                }
                couponCount.updateAndGet(v -> v + total);
                item.setCouponTotal(item.getCouponTotal() - total);
                couponConfigMapper.updateById(item);
            });
            map.put("newCouponCount", couponCount);
            map.put("newCouponList", list);
            redisUtil.hset(redisKey, String.valueOf(userId), JSON.toJSONString(map), RedisConstants.USER_NEW_COUPON_TIME);
        }
    }
}
